<template autoRoute="true">
  <div>
    <CToolbar
      :fields="fields"
      :visibleButtons="toolbarOptions"
      :search-fields="['name']"
      @openAddRecordDialog="handleAddLifecycle"
      @filter="handleFilter"
      @close="close"
      style="position: relative; top: 0; left: 0; padding: 8px 0"
    >
      <template #toolbar-right-before>
        <el-input
          v-model="searchName"
          placeholder="输入关键词"
          class="search-input"
          :prefix-icon="Search"
          @change="handleSearch"
          style="margin-right: 6px"
        />
      </template>
    </CToolbar>
    <div class="wbs-tree-container">
      <!-- 批量操作浮层 -->
      <CLBatchOpToolbar
        :show="showCLBatchOpToolbar"
        :selected-count="selectedRecords.length"
        @delete="handleBatchDelete"
      >
        <!--        <button class="batch-btn">修改属性</button>-->
        <!--        <button class="batch-btn">修改类型</button>-->
      </CLBatchOpToolbar>
      <CLTable
        v-loading="loading"
        :fields="fields"
        :initial-data="tableData"
        :router-fields="routerFields"
        :line-height="currentLineHeight"
        :more-actions="moreActions"
        :tableConfig="tableConfig"
        :page-query="tableListQuery"
        @pagerChange="pagerChange"
        @onMoreAction="handleMoreAction"
        @show:records="handleShowRecords"
      >
      </CLTable>
      <!-- 字段配置悬浮层 -->
      <FieldConfigPopup
        :fields="currentFields"
        :position="fieldConfigPosition"
        :visible="showFieldConfig"
        @close="showFieldConfig = false"
        @fieldsChange="handleFieldsChange"
      />
    </div>

    <CDialog
      :title="operate === 'create' ? '新建生命周期' : '编辑生命周期'"
      v-model="dialogVisible"
      @handleDialogOk="handleCreateOrEditLifecycle"
      :fields="dialogFields"
      :nodeData="selectedNode"
    ></CDialog>
  </div>
</template>
<script setup lang="ts">
  import { ElInput, ElMessage, ElMessageBox } from "element-plus";
  import { provide, reactive, ref } from "vue";
  import CLTable from "@/components/CLTable/index.vue";
  import CToolbar from "@/components/CToolbar.vue";
  import CDialog from "@/components/CDialog.vue";
  import type { DynamicField } from "@/data/wbsFields.ts";
  import { useRouter } from "vue-router";

  import {
    mockFieldsLifeResponse,
    mockFieldsLifeCreate,
  } from "@/data/wbsFields.ts";
  import {
    type LifeCycleEntity,
    type queryPagesType,
    type createLifeCycleParams,
  } from "@/interface/lifecycle.ts";
  import {
    createLifeCycle,
    deleteLifeCycle,
    listLifeCycle,
    copyLifeCycle,
    updateLifeCycle,
    deleteLifeCycleBatch,
  } from "@/api/lifeCycle.ts";
  import type { ProjectNode } from "@/data/wbsData.ts";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import { Search } from "@element-plus/icons-vue";

  const props = withDefaults(
    defineProps<{
      type: string;
    }>(),
    {
      type: "",
    },
  );

  const router = useRouter();
  const loading = ref(false);
  const operate = ref("create"); // CDialog 操作 create/edit
  const dialogVisible = ref(false); // CDialog 弹层展示
  const showCLBatchOpToolbar = ref(false);
  const selectedRecords = ref<LifeCycleEntity[]>([]);
  const searchName = ref("");

  // 工具栏选项
  const toolbarOptions = ref({
    add: {
      name: "新增",
      enable: true,
    },
    fieldConfig: false,
    filter: true,
    sort: false,
    lineHeight: false,
    help: false,
    log: false,
    export: false,
    search: false,
  });
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const routerFields = ref(["name", "statusName"]);
  const currentFields = ref<DynamicField[]>([]);
  const showFieldConfig = ref(false);
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );

  const handleShowRecords = (records: LifeCycleEntity[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
  };

  // 处理批量删除操作
  const handleBatchDelete = () => {
    console.log("selectedRecords", selectedRecords.value);
    if (selectedRecords.value.length === 0) return;
    ElMessageBox.confirm("确定删除该生命周期?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true,
    })
      .then(async () => {
        // deleteLifecycleAction(node.id!);
        const ids = selectedRecords.value.map((i) => i.id);
        await deleteLifeCycleBatch(ids);
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getLifecycleTableData();
        selectedRecords.value = [];
        showCLBatchOpToolbar.value = false;
      })
      .catch(() => {});
    // 删除完成后清空选中状态
  };
  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  const addRecord = (newRecords: ProjectNode[]) => {
    tableData.value = [...newRecords];
  };

  // 提供给所有子孙组件使用
  provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);
  const dialogFields = ref<DynamicField[]>(mockFieldsLifeCreate); // 创建、编辑表单动态展示项
  const fields = ref<DynamicField[]>([]); // table表格展示列
  const tableListQuery = reactive<queryPagesType>({
    pageNo: 1,
    pageSize: 20,
    sortParams: [],
    conditions: [],
    total: 0,
  }); // table列表请求参数
  const tableData = ref<LifeCycleEntity[]>([]); // table数据
  const selectedNode = ref<LifeCycleEntity>({} as LifeCycleEntity);
  const moreActions = ref([
    { key: "edit", label: "编辑" },
    { key: "delete", label: "删除" },
    // { key: "copy", label: "复制" },
    // { key: "toSetting", label: "设置" },
  ]);
  const tableConfig = ref({
    editable: false,
    borderMode: "none",
    tableH: "calc(100vh - 175px)",
    showOperationsColumn: true, // 是否显示操作列
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    OperationsColumnWidth: 80, //自定义操作列宽度
    frozenColCount: 0, // 冻结前面列数
    rightFrozenColCount: 0, // 冻结后面列数
    page: {
      enable: true,
      totals: 0,
    },
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    // rowSeriesNumber: {
    //   dragOrder: true, // 开启行号拖拽排序
    // },
    // borderMode: "none", // 表格边框模式，none为无边框
  });
  const getFields = () => {
    fields.value = mockFieldsLifeResponse;
  };
  getFields();
  const typeMap = {
    TASK: "任务",
    PROJECT: "项目",
  };
  const statusMap = {
    DISABLE: "禁用",
    NORMAL: "开启",
  };
  const getLifecycleTableData = async () => {
    loading.value = true;
    if (props.type) {
      tableListQuery.conditions.push({
        field: "type",
        operator: "=",
        value: props.type,
      });
    }
    tableListQuery.conditions.push({
      field: "managementVisible",
      operator: "=",
      value: "YES",
    });
    const res = await listLifeCycle(tableListQuery);
    loading.value = false;
    tableListQuery.conditions = []; // 清空条件
    tableData.value =
      res.result?.map((item) => {
        item.typeName = typeMap[item.type];
        item.statusName = item.status !== "DISABLE";
        return item;
      }) || [];
    tableListQuery.total = res.total;
  };
  getLifecycleTableData();
  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  const pagerChange = (pager: { currentPage: number; pageSize: number }) => {
    tableListQuery.pageSize = pager.pageSize;
    tableListQuery.pageNo = pager.currentPage;
    getLifecycleTableData();
  };
  const handleMoreAction = async (action: string, node: LifeCycleEntity) => {
    console.log("handleMoreAction", action, node);
    if (action === "edit") {
      operate.value = "edit";
      selectedNode.value = { ...node };
      dialogVisible.value = true;
    } else if (action === "delete") {
      ElMessageBox.confirm("确定删除该生命周期?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      })
        .then(() => {
          deleteLifecycleAction(node.id!);
        })
        .catch(() => {});
    } else if (action === "copy") {
      copyLifecycleActive(node.id!);
    } else if (action === "name") {
      router.push(
        `/pm/globalSetting/lifecycleDetail?id=${node.id!}&lifecycle=${encodeURIComponent(node.name!)}`,
      );
    } else if (action === "statusName") {
      const params: createLifeCycleParams = {
        id: node.id,
        name: {
          zh_CN: node.name,
        },
        remark: node.remark,
        status: node.status === "DISABLE" ? "NORMAL" : "DISABLE",
        type: node.type,
      };
      // params.status = params.status === "DISABLE" ? "NORMAL" : "DISABLE";
      await updateLifeCycle(params);
      ElMessage({
        type: "success",
        message: "编辑成功",
      });
      getLifecycleTableData();
    }
  };
  // 处理筛选事件
  const handleFilter = (condition: string, direction: "asc" | "desc") => {
    console.log("筛选条件:", condition, "排序方向:", direction);
  };
  const deleteLifecycleAction = async (id: string) => {
    await deleteLifeCycle(id);
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getLifecycleTableData();
  };
  const copyLifecycleActive = async (id: string) => {
    await copyLifeCycle(id);
    ElMessage({
      type: "success",
      message: "复制成功",
    });
    getLifecycleTableData();
  };
  const close = () => {};
  // 处理搜索事件
  const handleSearch = () => {
    tableListQuery.conditions.push({
      field: "name",
      operator: "like",
      value: searchName,
    });
    getLifecycleTableData();
  };
  const handleAddLifecycle = () => {
    //
    dialogVisible.value = true;
    operate.value = "create";
  };

  const handleCreateOrEditLifecycle = async (formData: Record<string, any>) => {
    if (operate.value === "create") {
      const params: createLifeCycleParams = {
        name: {
          zh_CN: formData.name,
          en_US: "task lifecycle test2",
        },
        type: props.type,
        model: "",
        status: formData.status,
        remark: formData.remark,
        statusCard: "",
        layout: "",
      };
      await createLifeCycle(params);
      ElMessage({
        message: "创建成功",
        type: "success",
      });
      dialogVisible.value = false;
      getLifecycleTableData();
    } else {
      // const params = {
      //   ...selectedNode.value,
      //   ...formData,
      //   name: {
      //     zh_CN: formData.name,
      //     en_US: "task lifecycle test2",
      //   },
      // };
      // delete params.i18nColumnMap;
      await updateLifeCycle({
        id: selectedNode.value.id,
        ...formData,
        name: {
          zh_CN: formData.name,
          en_US: "task lifecycle test2",
        },
      } as createLifeCycleParams);
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
      dialogVisible.value = false;
      getLifecycleTableData();
    }
    console.log(formData, "handleCreateLifecycle");
  };
</script>

<style scoped>
  .wbs-container {
    background-color: #ffffff;
  }

  .wbs-tree-container {
    background-color: #fff;
    position: relative;
  }

  .batch-btn {
    padding: 4px 12px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 12px;
    color: #42464e;
  }

  .batch-btn:hover {
    color: #42464e;
    background-color: rgba(31, 35, 41, 0.1);
  }

  /* 滚动条样式 */
  .wbs-tree-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .wbs-tree-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb:hover {
    background: #555;
  }
</style>
